package com.agri.controller;

import com.agri.dto.ProductQueryDTO;
import com.agri.entity.FinancingProduct;
import com.agri.result.Result;
import com.agri.service.FinancingProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 融资产品控制器
 * 提供融资产品的CRUD操作和管理接口
 *
 * @author Agri-Fin-Sale Team
 * @since 2025-11-05
 */
@RestController
@RequestMapping("/financing/product")
public class FinancingProductController {
    @Autowired
    private FinancingProductService financingProductService;

    /**
     * 创建融资产品
     * 需要ADMIN角色权限
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> create(@Valid @RequestBody FinancingProduct product) {
        return financingProductService.createProduct(product);
    }

    /**
     * 更新融资产品
     * 需要ADMIN角色权限
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> update(@PathVariable Long id, @Valid @RequestBody FinancingProduct product) {
        product.setId(id);
        return financingProductService.updateProduct(product);
    }

    /**
     * 删除融资产品
     * 需要ADMIN角色权限
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> delete(@PathVariable Long id) {
        return financingProductService.deleteProduct(id);
    }

    /**
     * 根据ID获取融资产品详情
     */
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return financingProductService.getProductById(id);
    }

    /**
     * 查询融资产品列表
     * 支持按类型、状态等条件筛选
     */
    @GetMapping("/list")
    public Result<?> list(ProductQueryDTO queryDTO) {
        return financingProductService.listProducts(queryDTO);
    }

    /**
     * 推荐融资产品
     * 根据用户信息和需求推荐合适的融资产品
     */
    @PostMapping("/recommend")
    public Result<?> recommend(@RequestParam Long userId, 
                              @RequestParam(required = false) String cropType,
                              @RequestParam(required = false) Double loanAmount) {
        return financingProductService.recommendProducts(userId, cropType, loanAmount);
    }

    /**
     * 上下架融资产品
     * 需要ADMIN角色权限
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        return financingProductService.updateProductStatus(id, status);
    }
}